/*
 * PersonMonitor.java
 *
 * Created on August 19, 2007, 12:44 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package timeitj.persistence.monitors;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import org.apache.log4j.Logger;
import timeitj.persistence.Group;
import timeitj.persistence.Person;

import java.sql.Connection;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 *
 * @author wallner
 */
public class PersonMonitor {
   
    @Resource(name="timeitjDB",mappedName="timeitjDB",type=javax.sql.DataSource.class)
     
    private Logger logger = Logger.getLogger(PersonMonitor.class.getName());
    
    private String insertStatement = "INSERT INTO AUTHGROUP "
        + "(LOGIN, GROUPNAME) "
        + "VALUES (?, ?)";
    
    private String deleteStatement = "DELETE FROM AUTHGROUP "
        + "WHERE LOGIN = ?";
    
    private DataSource datasource;
    private Connection connection;
    
    /** Creates a new instance of PersonMonitor */
    public PersonMonitor() {
        
        Context ctx;
        try {
            ctx = new InitialContext();
            datasource = (DataSource) ctx.lookup("timeitjDB");
        } catch (NamingException ex) {
            logger.fatal("Can't lookup datasource", ex);
        }
        try {
            connection = datasource.getConnection(); 
        } catch (SQLException ex) {
            logger.fatal("Can't get connection", ex);
        } 
    }
    
    protected void finalize(){
        try{
            connection.close();
        } catch (SQLException ex){
            logger.fatal("Can't close connection", ex);
        }
    }
    
     
    @PrePersist
    @PreUpdate
    public void updateHelperTable(Person person) throws SQLException{
        // Sicherstellen, dass user <-> nicht drinn ist
        removeFromHelperTable(person);
        PreparedStatement ps = connection.prepareStatement(insertStatement);
        
        for (Group group:person.getGroups()){
            logger.info("Inserting " + person.getLogin() + " into helpertable");
            logger.info("Inserting " + group.getGroupName() + " into helpertable");
            ps.setString(1, person.getLogin());
            ps.setString(2, group.getGroupName());
            ps.executeUpdate();
            ps.close();
        }

    }
    
    @PreRemove
    public void removeFromHelperTable(Person person) throws SQLException{
        logger.info("Clearing helper table");
        PreparedStatement ps = connection.prepareStatement(deleteStatement);
        ps.setString(1, person.getLogin());
        ps.executeUpdate();
        ps.close();
    }
}
